<?php
require_once(dirname(__FILE__).'/../include/config.inc.php');
header('Content-type: application/json;charset=utf-8');
require_once "WxApi.php";
require_once "WxConfig.php";
require_once(dirname(__FILE__).'/../jssdk.php');
$url=$_GET['url'];
$aa="";
if(empty($url)){
	$errno=array('errno'=>-1);
}else{
	$appId=WxConfig::APPID;
	$appSecret=WxConfig::APPSECRET;
	$jssdk = new JSSDK($appId, $appSecret);
	$g_AccessToken=$jssdk->getAccessToken();
	//短网址存库
	$is_indb=$dosql->GetOne("select * from `#@__shorturl`  where trueurl='$url' ");
	if($is_indb){
		$aa=$is_indb['shorturl'];
	}else{
		$json='{"action":"long2short","long_url":"'.$url.'"}';
		$aa=doShortURL($json);
		//存库
		$time=time();
		$dosql->ExecNoneQuery("insert into `#@__shorturl`(trueurl,shorturl,addtime) values ('$url','$aa','$time')");
	}
	$errno=array('errno'=>0);
}
$json_json=array_merge($errno,array('url'=>$aa));
$data=json_encode($json_json);
echo $data;



function doShortURL($json){
		//发送消息
	global $g_AccessToken;
	$short_url="";
	if(isset($g_AccessToken)){
		$uuu="https://api.weixin.qq.com/cgi-bin/shorturl?access_token=".$g_AccessToken;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $uuu);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);  //https协议
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
		$html = curl_exec($ch);
		
		$json_arr=json_decode($html,true);
		if($json_arr['errcode']==0){
			$short_url=$json_arr['short_url'];
		}
		return $short_url;
	}
}